import HttpRequest from '@/utils/fetch'
import { AxiosRequestConfig, AxiosError } from 'axios'

const baseUrl = import.meta.env.VITE_APP_SERVER
const mode = import.meta.env.MODE
const request = new HttpRequest({
  baseURL: baseUrl,
  timeout: 10000,
})
// 本地运行使用慕课网防盗API，需获取icode（课程右侧项目校验码,30天有效）添加到参数中
if (mode === 'development') {
  request.instance.interceptors.request.use(
    // 发送请求前执行
    (config: AxiosRequestConfig) => {
      config.params = { ...config.params, icode: import.meta.env.VITE_APP_ICODE }
      if (config.data instanceof FormData) {
        config.data.append('icode', import.meta.env.VITE_APP_ICODE)
      } else {
        config.data = { ...config.data, icode: import.meta.env.VITE_APP_ICODE }
      }
      return config
    },
    // 请求错误执行
    (error: AxiosError) => {
      return Promise.reject(error)
    }
  )
}
export interface RequestDto<T> {
  code: number
  data: T
  msg: string
}
export interface RequestError {
  code: number
  error: string
}
export interface PageData<T> {
  count: number
  currentPage: number
  list: T[]
  pageSize: number
}
export interface PageParams {
  currentPage: number
  pageSize: number
}

export default request.instance
